#!/usr/bin/env python3
# HFT系统监控工具

import psutil
import time
import json
import socket
from datetime import datetime
import matplotlib.pyplot as plt

class HFTSystemMonitor:
    def __init__(self, config_path='config/monitor_config.json'):
        self.config = self.load_config(config_path)
        self.metrics = {
            'cpu': [],
            'memory': [],
            'network': [],
            'orders': [],
            'latency': []
        }
        
    def load_config(self, path):
        """加载监控配置"""
        with open(path) as f:
            return json.load(f)
    
    def collect_system_metrics(self):
        """收集系统指标"""
        while True:
            timestamp = datetime.now().isoformat()
            
            # CPU使用率
            cpu_percent = psutil.cpu_percent(interval=1)
            self.metrics['cpu'].append({
                'timestamp': timestamp,
                'value': cpu_percent
            })
            
            # 内存使用
            mem = psutil.virtual_memory()
            self.metrics['memory'].append({
                'timestamp': timestamp,
                'total': mem.total,
                'used': mem.used,
                'percent': mem.percent
            })
            
            # 网络活动
            net = psutil.net_io_counters()
            self.metrics['network'].append({
                'timestamp': timestamp,
                'bytes_sent': net.bytes_sent,
                'bytes_recv': net.bytes_recv
            })
            
            time.sleep(self.config['collection_interval'])
    
    def analyze_latency(self, log_file):
        """分析订单执行延迟"""
        with open(log_file) as f:
            for line in f:
                if 'OrderExecuted' in line:
                    data = json.loads(line.split('OrderExecuted')[-1])
                    latency = (data['exec_time'] - data['send_time']).total_seconds() * 1000  # 毫秒
                    self.metrics['latency'].append(latency)
    
    def generate_report(self):
        """生成性能报告"""
        # CPU使用率图表
        plt.figure(figsize=(10, 6))
        timestamps = [m['timestamp'] for m in self.metrics['cpu']]
        values = [m['value'] for m in self.metrics['cpu']]
        plt.plot(timestamps, values)
        plt.title('CPU Usage Over Time')
        plt.savefig('reports/cpu_usage.png')
        
        # 延迟分布图
        plt.figure(figsize=(10, 6))
        plt.hist(self.metrics['latency'], bins=50)
        plt.title('Order Execution Latency Distribution')
        plt.savefig('reports/latency_distribution.png')
        
        # 保存原始数据
        with open('reports/performance_report.json', 'w') as f:
            json.dump(self.metrics, f, indent=2)
    
    def start(self):
        """启动监控"""
        try:
            self.collect_system_metrics()
        except KeyboardInterrupt:
            self.generate_report()

if __name__ == '__main__':
    monitor = HFTSystemMonitor()
    monitor.start()